<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Facebooklogin extends CI_Controller{
	
	public function __construct()
	{	
		parent::__construct();
		$this->load->model('Fblogin_model');
	}
	public function index()
	{	//echo 'hii'; die;
		/*$app_id 	= '337888192916545';
  		$app_secret = 'd4434555b0b345c3cf889ff9c355d7c6';*/ 
  		$app_id 	= '456595961099607';
  		$app_secret = 'de3b388ad4091dd2736cae8ed016fba0';
		$my_url		= $this->config->base_url().'facebooklogin';
		
  		$code 		= $_GET["code"];
 
		 //auth user
		 if(empty($code)) {
			 			
						$dialog_url = 'https://www.facebook.com/dialog/oauth?client_id='.$app_id.'&redirect_uri='.urlencode($my_url);
						echo("<script>top.location.href='".$dialog_url."'</script>");
		  }

		
  		//get user access_token
  		$token_url = 'https://graph.facebook.com/oauth/access_token?client_id='.$app_id. '&redirect_uri='.urlencode($my_url).'&client_secret='.$app_secret.'&code='.$code;
  		$access_token = file_get_contents($token_url);
 
  		// Run fql query
 		//$fql_query_url = 'https://graph.facebook.com/'.'/fql?q=SELECT+uid,name,pic_square_with_logo,username,email,verified,pic,pic_small,pic_big,pic,sex,birthday_date,religion,first_name,last_name,current_address,current_location,hometown_location,religion+FROM+user+WHERE+uid=me()'.'&'.$access_token;
		
		$fql_query_url = 'https://graph.facebook.com/'.'/fql?q=SELECT+uid,name,pic_square_with_logo,relationship_status,username,email,verified,pic,pic_small,pic_big,pic,sex,birthday_date,religion,first_name,last_name,current_address,current_location,hometown_location,religion+FROM+user+WHERE+uid+IN+(SELECT+uid2+FROM+friend+WHERE+uid1=me())+order+by+first_name'.'&'.$access_token;
  		$fql_query_result = file_get_contents($fql_query_url);
  		$fql_query_obj = json_decode($fql_query_result, true);

		//  ++++++++       user face book logout    ++++++++++++++++
		/*echo $fb_logout_url	=	"http://www.facebook.com/logout.php?api_key=".$app_id."&v=1.0&auth_token=".$access_token."&confirm=1";
		echo $fb_logout_url_token = file_get_contents($fb_logout_url);die;*/
		
  		//display results of fql query
  		echo '<pre>';
  		print_r("query results:");
  		print_r($fql_query_obj);
		print_r($this->session->userdata);
  		echo '</pre>';
		die;
		if(is_array($fql_query_obj['data']) && count($fql_query_obj['data']))
		{
			if($this->Fblogin_model->login_with_fb($fql_query_obj)) {
				$this->session->set_userdata('login_with_fb','1');
				redirect($this->config->base_url().'profile/edit');
			}
			else {
				redirect($this->config->base_url());
			}
		}
		else {
				//redirect($this->config->base_url());
				echo '<script>';
				echo 'window.location.href="'.$this->config->base_url().'"';				
				echo '</script>';
				header('Location: '.$this->config->base_url());
		}
	}
}
?>